<template>
  <h1>轮播图列表</h1>
  <hr />
  <el-table :data="BannerList" style="width: 100%" height="95%">
    <el-table-column fixed prop="bannerid" label="轮播图编号" width="230" />
    <el-table-column label="图片" width="240">
      <template #default="scope">
        <img class="img" :src="scope.row.img" alt="" style="height: 150px;"/>
      </template>
    </el-table-column>
    <el-table-column prop="alt" label="图片名称" width="160" />
    <el-table-column prop="link" label="图片提示" width="280" />
    <el-table-column label="是否启用" width="200" v-if="crud.charAt(0)=='1'">
      <template #default="scope">
        <el-switch
          style="--el-switch-on-color: #76b1e1"
          v-model="scope.row.flag"
          @change="(val:boolean)=>updateBannerFlag(scope.row.bannerid,val)"
        />
      </template>
    </el-table-column>
    <el-table-column label="删除" width="200" v-if="crud.charAt(3)=='1'">
      <template #default="scope">
        <el-popconfirm
          title="确定要删除么?删了就没有了噢?"
          @confirm="delBanner(scope.row.bannerid)"
        >
          <template #reference>
            <el-button size="small" type="danger"> Delete </el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import "element-plus/dist/index.css";
import { useRoute } from "vue-router";
// 导入封装好的请求
import { banner_delete, banner_list, banner_updateFlag} from "../../../utils/api";

interface IBanner {
  bannerid: string;
  img: string;
  alt: string;
  link: string;
  flag: boolean;
}

// 存放轮播图数据
let BannerList = reactive<IBanner[]>([]);

// 获取轮播图数据
const getBannerList = () => {
  banner_list().then((res: any) => {
    if (res.data.code === "200") {
      BannerList.length = 0;
      BannerList.push(...res.data.data);
    }
  });
};

getBannerList();
// 获取用户的增删改查权限
const $route = useRoute();
const crud:string = ($route.meta.crud as string);
// 更新轮播图的是否启用(访问状态)
const updateBannerFlag = (bannerid: string, val: boolean) => {
  banner_updateFlag({bannerid,flag:val}).then((res) => {
    if (res.data.code === "200") {
      ElMessage({
        message: "访问状态更新成功！",
        type: "success",
      });
    }
  });
};

// 删除单条轮播图
const delBanner = (bannerid: string) => {
  banner_delete({bannerid}).then((res) => {
    if (res.data.code === "200") {
      // alert("删除成功");
      ElMessage({
        message: "删除成功！",
        type: "success",
      });
      // 利用删除后重新发送请求获取最新数据(多发了一次请求)
      getBannerList();
    }
  });
};
</script>

<style scoped>
.img {
  width: 200px;
  height: 150px;
}
</style>